package com.tgky.ybzb.tasks;

import com.tgky.ybzb.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 监听算法端口
 */
@Component
public class AlgorithmListenPortTask {
//    @Autowired
//    private SimpMessagingTemplate wsTemplate;

    @Scheduled(cron = "0/1 * * * * ?")
    public Result udpTest() throws IOException {
        DatagramSocket socket = null;
        try {
            System.out.println("定时任务开启");
            socket = new DatagramSocket(9000);
            while (true) {
                byte[] data = new byte[4096];
                DatagramPacket packet = new DatagramPacket(data, data.length);
                socket.receive(packet);
                String info = new String(data, 0, packet.getLength());
//                JSONObject jsonObject = JSONObject.parseObject(info);
                // 向前端推送websocket数据
//                wsTemplate.convertAndSend("/topic/udpData", info);
                System.out.println(info);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } finally {
            System.out.println("UDP接收 socket 关闭");
            socket.close();
        }
        return Result.success();
    }
}
